package com.puhui.lib.base;

import android.content.Intent
import android.os.Bundle
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.blankj.utilcode.util.BarUtils
import com.puhui.lib.R
import com.puhui.lib.base.dialog.LoadingDialog
import com.puhui.lib.base.mvp.IView
import com.puhui.lib.utils.ToastUtil
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity
import org.greenrobot.eventbus.EventBus

abstract class BaseActivity<T : ViewDataBinding> : RxAppCompatActivity(), IView {

    open lateinit var mContentView: T
    private var mLoadingDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mContentView = DataBindingUtil.setContentView(this, getLayoutId())

        setStatusBar(getStatusBarColor(), isFullScreen(), isLightMode())

        if (needEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mLoadingDialog = LoadingDialog()
        init(savedInstanceState)
    }

    fun setStatusBar(@ColorRes color: Int, isFullScreen: Boolean, isLightMode: Boolean) {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, color))
        BarUtils.setStatusBarVisibility(this, isFullScreen)
        BarUtils.setStatusBarLightMode(this, isLightMode)
    }

    protected open fun getStatusBarColor(): Int = R.color.white

    protected open fun isFullScreen(): Boolean = true

    protected open fun isLightMode(): Boolean = true

    abstract fun init(savedInstanceState: Bundle?)

    abstract fun getLayoutId(): Int

    open fun needEventBus() = false

    override fun onDestroy() {
        if (needEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    override fun startActivity(clazz: Class<*>) {
        startActivity(Intent(this, clazz))
    }

    override fun startActivityForResult(clazz: Class<*>, requestCode: Int) {
        startActivityForResult(Intent(this, clazz), requestCode)
    }

    override fun isAvailable(): Boolean {
        return !isFinishing
    }

    override fun startLoading(text: String?) {
        mLoadingDialog?.let {
            if (!it.isVisible) it.show(this)
        }
    }

    override fun stopLoading() {
        mLoadingDialog?.let {
            if (it.isVisible) it.dismiss()
        }
    }

    override fun showToast(message: String?) {
        ToastUtil.showToast(message)
    }

    override fun showToast(resourceId: Int) {
    }

    override fun getTopActivity() = this

    override fun getTopContext() = this

    override fun getResColor(@ColorRes colorRes: Int) = ContextCompat.getColor(this, colorRes)
}
